package com.fq.api.exception;

import com.fq.api.api.ApiError;
import com.fq.api.api.ApiRest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;


/**
 * @Author 超chao
 * @Description 全局异常处理器，用于统一处理系统中的各类异常
 * @Date 2024/10/12/周六 14:02
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice
public class ServiceExceptionHandler {

    /**
     * Shiro异常
     * @param e
     * @return
     */
    @ExceptionHandler({AuthorizationException.class})
    @ResponseStatus(HttpStatus.OK)
    public ApiRest<Void> shiroExceptionHandler(AuthorizationException e) {
        return new ApiRest<>(new ServiceException(ApiError.ERROR_10030000));
    }

    /**
     * 捕获ServiceException
     * @param e
     * @return
     */
    @ExceptionHandler({ServiceException.class})
    @ResponseStatus(HttpStatus.OK)
    public ApiRest<Void> serviceExceptionHandler(ServiceException e) {
        return new ApiRest<>(e);
    }

    /**
     * 捕获参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiRest<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        return new ApiRest<Void>().setMsg(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage()).setCode(1);
    }
}